package com.tms.common.core.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis分布式锁服务类
 * 提供基于Redisson的分布式锁功能
 */
@Component
public class RedisLockService {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 获取分布式锁
     *
     * @param lockKey 锁的键
     * @return 锁对象
     */
    public RLock getLock(String lockKey) {
        return redissonClient.getLock(lockKey);
    }

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey    锁的键
     * @param waitTime   等待时间（秒）
     * @param leaseTime  持有锁的时间（秒）
     * @return 是否获取成功
     */
    public boolean tryLock(String lockKey, long waitTime, long leaseTime) {
        try {
            RLock lock = getLock(lockKey);
            return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 释放分布式锁
     *
     * @param lockKey 锁的键
     */
    public void unlock(String lockKey) {
        RLock lock = getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
    
    /**
     * 使用分布式锁执行操作
     *
     * @param lockKey    锁的键
     * @param waitTime   等待时间（秒）
     * @param leaseTime  持有锁的时间（秒）
     * @param runnable   要执行的操作
     * @return 是否执行成功
     */
    public boolean executeWithLock(String lockKey, long waitTime, long leaseTime, Runnable runnable) {
        boolean locked = false;
        try {
            locked = tryLock(lockKey, waitTime, leaseTime);
            if (locked) {
                runnable.run();
                return true;
            } else {
                return false;
            }
        } finally {
            if (locked) {
                unlock(lockKey);
            }
        }
    }
}
